package com.uziot.bucket.ftp.thread;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author Lenovo
 */
public class ThreadDemo extends Thread {

    private RandomAccessFile read = null;
    private RandomAccessFile write = null;
    private long start;
    private long end;
    private String srcPath;
    private String DestPath;

    ThreadDemo(long start, long end, String srcPath, String DestPath) {
        this.start = start;
        this.end = end;
        this.srcPath = srcPath;
        this.DestPath = DestPath;
    }

    @Override
    public void run() {
        try {
            this.read = new RandomAccessFile(srcPath, "r");
            this.write = new RandomAccessFile(DestPath, "rw");
            read.seek(start);
            write.seek(start);
            byte[] bytes = new byte[1024];
            int n = 0;
            while ((n = read.read(bytes)) != -1) {
                if (start + n > end) { //最后一次读取；
                    n = (int) (end - start) + 1;
                    start = end + 1; //为了跳出循环
                }
                write.write(bytes, 0, n);
                if (start > end) {
                    break;
                }
                start += n;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (this.read != null) {
                try {
                    this.read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (this.write != null) {
                try {
                    this.write.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

